<template>
  <div class="pagination">
    <button @click="sendPageNo(pageNo - 1)" :disabled="pageNo === 1">
      上一页
    </button>
    <button v-show="startAndEnd.start > 1" @click="sendPageNo(1)">1</button>
    <button v-show="startAndEnd.start > 2">...</button>
    <button
      :class="{ active: pageNo === startAndEnd.start + index }"
      v-for="(_, index) in continues"
      :key="_"
      @click="sendPageNo(startAndEnd.start + index)"
    >
      {{ startAndEnd.start + index }}
    </button>
    <button v-show="totalPage > startAndEnd.end + 1">···</button>
    <button v-show="totalPage > startAndEnd.end" @click="sendPageNo(totalPage)">
      {{ totalPage }}
    </button>
    <button @click="sendPageNo(pageNo + 1)" :disabled="pageNo === totalPage">
      下一页
    </button>
    <span>共 {{ total }} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    pageNo: {
      type: Number,
      default: 1,
    },
    pageSize: {
      type: Number,
      default: 5,
    },
    continues: {
      type: Number,
      default: 5,
    },
    total: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    // 1、总页码
    totalPage() {
      // 总页码 = 总条数 / 每页条数 (向上取整);
      const totalPage = Math.ceil(this.total / this.pageSize);
      return totalPage;
    },
    // 2. 计算连贯页码的起始和结束
    startAndEnd() {
      const { pageNo, continues, totalPage } = this;
      let start, end;
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNo - Math.floor(continues / 2);
        end = pageNo + Math.floor(continues / 2);

        if (start < 1) {
          start = 1; //起始页的最小页码只能等于 一
          end = continues;
        }

        if (end > totalPage) {
          end = totalPage; //连贯页码的最后页码 只能等于总页码
          start = totalPage - continues + 1;
        }
      }
      return { start, end };
    },
  },
  methods: {
    sendPageNo(val) {
      this.$emit("setPageNo", val);
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
